package cn.jinjimi.framework.plugin;

import android.content.Context;

import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.app.AccountManager;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Hiro on 15/6/2.
 */
public class PluginManager {

    public static final int LIMIT_ERR = 0x1;
    public static final int TYPE_NOT_SUPPORT = 0x2;
    public static final int OPENED = 0x2;

    private static final String TAG = PluginManager.class.getSimpleName();

    private Map<Class<? extends BasePlugin>, PluginLauncher> mPlugLauncher;

    public PluginManager(){
        mPlugLauncher = new HashMap<Class<? extends BasePlugin>, PluginLauncher>();
    }

    /**
     * 启动插件
     * @param context
     * @param plugin
     */
    public int launch(Context context, Plugin plugin) {
        PluginLauncher launcher = findLauncher(plugin.getType());

        LogUtil.d(TAG, "check plugin launcher...");
        if(launcher==null)
            return TYPE_NOT_SUPPORT;

        LogUtil.d(TAG, "check plugin limit...");
        if(plugin.getLimit() == PluginLimit.LOGIN
                && !AccountManager.getInstance().isLogin()){
            return LIMIT_ERR;
        }

        LogUtil.d(TAG, "start launch plugin...");
        launcher.launch(context, plugin);

        return OPENED;
    }

    /**
     * 添加插件启动器
     * @param type
     * @param launcher
     */
    public void addLauncher(Class<? extends BasePlugin> type, PluginLauncher launcher){
        mPlugLauncher.put(type, launcher);
    }

    /**
     * 查找插件启动器
     * @param type
     * @return
     */
    public PluginLauncher findLauncher(Class<? extends BasePlugin> type) {
        return mPlugLauncher.get(type);
    }

}
